package com.woniu.controller;

import com.baomidou.mybatisplus.generator.IFill;
import com.woniu.entity.UserRegisterDTO;
import com.woniu.pojo.User;
import com.woniu.service.IUserService;
import com.woniu.util.MobileUtil;
import com.woniu.util.Result;
import com.woniu.util.SendSmsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/user")
public class UserController extends BaseController {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    IUserService userService;


    @RequestMapping("/toRegister")
    public String toRegister() {
        return "register";
    }

    @RequestMapping("/toLogin")
    public String toLogin() {
        return "login";
    }


    @GetMapping("/sendSms/{phone}/{action}")
    @ResponseBody
    public Result tosendSms(@PathVariable String phone, @PathVariable String action, HttpSession session) {
        //校验传入的手机号码
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(action)) {
            return error("手机号码不能为空");
        }
        boolean flag = MobileUtil.checkPhone(phone);
        if (!flag) {
            return error("请输入正确的手机号码");
        }
        //调用工具类中的方法，生成随机数作为验证码
        String code = SendSmsUtil.getRandomNum(4);

        //先判断该手机号码在该场景有没有过期的短信，有过期的短信，不发了，如果没有，发送短信
        Object redisCode = redisTemplate.opsForValue().get("code_" + action + "_" + phone);

        if (redisCode != null) {
            return error("已发送验证码，请注意查收");
        }

        //将生成的验证码，保存到session中
        //注意 这里的Key名字不能随便起，要考虑场景(action)和对象(phone)
//        session.setAttribute("code_" + action + "_" + phone, code);
        // 4. 将生成的验证码存储到Redis中
        redisTemplate.opsForValue().set("code_" + action + "_" + phone, code, 5 * 60, TimeUnit.SECONDS);


        String number = (String) redisTemplate.opsForHash().get("sendSms", "time_" + action + "_" + phone);

        //判断是不是第一次获取验证码，第一次的话查出来应该为null
        if (number == null) {
            int count = 5;
            number = String.valueOf(count);
            redisTemplate.opsForHash().put("sendSms", "time_" + action + "_" + phone, number);

        }
        if ("0".equals(number)) {
            return error("今天的次数已经用完了");
        }
        Integer currentCount = Integer.valueOf(number) - 1;
        number = String.valueOf(currentCount);

        redisTemplate.opsForHash().put("sendSms", "time_" + action + "_" + phone, number);

        //调用工具类发送短信
//        SendSmsUtil.sendSms(phone,code);
        return success();
    }


    @PostMapping("/register")
    @ResponseBody
    public Result tosendSms(@RequestBody UserRegisterDTO userRegisterDTO, HttpSession session) {
        //原始版本使用session去存，这里用更高级的redis去解决
        if (StringUtils.isEmpty(userRegisterDTO.getPhone()) || StringUtils.isEmpty(userRegisterDTO.getPassword()) || StringUtils.isEmpty(userRegisterDTO.getCode())) {
            return error("请正确填写信息");
        }

        boolean flag = MobileUtil.checkPhone(userRegisterDTO.getPhone());
        if (!flag) {
            return error("请填写正确的手机号码");
        }
        // 判断验证码是否正确 跟session中保存的值进行比较
//        String sessionCode = (String) session.getAttribute("code_register_" + userRegisterDTO.getPhone());
        String redisCode = (String) redisTemplate.opsForValue().get("code_register_" + userRegisterDTO.getPhone());


        if (redisCode == null || !redisCode.equals(userRegisterDTO.getCode())) {
            return error("验证码不正确");
        }
        // 删除session中的验证码
//        session.removeAttribute("code_register_" + userRegisterDTO.getPhone());

        redisTemplate.delete("code_register_" + userRegisterDTO.getPhone());

        // 3. 调用service的注册方法，进行注册（保存）
        userService.register(userRegisterDTO);// 9544

        // 4. 返回结果
        return success();
    }


    @PostMapping("/login")
    @ResponseBody
    public Result logintoIndex(@RequestBody UserRegisterDTO userRegisterDTO, HttpSession session) {
       //1.对数据进行规则校验
        if (StringUtils.isEmpty(userRegisterDTO.getPhone()) || StringUtils.isEmpty(userRegisterDTO.getCode())) {
            return error("请正确填写信息");
        }

        boolean flag = MobileUtil.checkPhone(userRegisterDTO.getPhone());
        if (!flag) {
            return error("请填写正确的手机号码");
        }
        //2. 判断验证码是否正确 跟session中保存的值进行比较
//        String sessionCode = (String) session.getAttribute("code_register_" + userRegisterDTO.getPhone());
        String redisCode = (String) redisTemplate.opsForValue().get("code_login_" + userRegisterDTO.getPhone());


        if (redisCode == null || !redisCode.equals(userRegisterDTO.getCode())) {
            return error("验证码不正确");
        }
        // 删除session中的验证码
//        session.removeAttribute("code_register_" + userRegisterDTO.getPhone());

        redisTemplate.delete("code_login_" + userRegisterDTO.getPhone());

        // 3. 判断手机号码是否已经被注册（根据手机号码查询用户信息）
           User user = userService.getByPone(userRegisterDTO.getPhone());// 9544
      if (user == null){
          return error("该账号不存在,请先注册再登录");
      }

        // 4. 如果登录成功，将用户的信息保存到session中
        session.setAttribute("user",user);

        // 5. 返回结果
        return success();
    }




}
